package admin

import (
	"ginadmin/app/dao"
	"ginadmin/app/model"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type MenuController struct {
	BaseController
}

// 菜单列表页面
func (con MenuController) MenuIndex(c *gin.Context) {
	c.HTML(http.StatusOK, "menu/index.html", gin.H{
		"title": "这是标题",
	})
}

// 菜单添加/编辑
func (con MenuController) MenuPostPage(c *gin.Context) {

	//编辑查询数据
	menu := &model.AdminMenu{}

	strid := c.DefaultQuery("id", "0")
	id, _ := strconv.ParseUint(strid, 10, 64)

	if id > 0 {
		menu.ID = uint(id)

		//查询菜单
		dao.DB.First(&menu)
	}

	c.HTML(http.StatusOK, "menu/edit.html", gin.H{
		"info": menu,
		"id":   id,
	})
}

type Test struct {
	ID uint `json:"id"`
}

// 添加编辑提交
func (con MenuController) MenuPost(c *gin.Context) {

	var menu model.AdminMenu
	//err := json.NewDecoder(c.Request.Body).Decode(&menu)

	c.ShouldBind(&menu)

	//验证路由重复
	var hrefck model.AdminMenu

	strpid := c.DefaultPostForm("plist_select_nodeId", "0")

	pid, _ := strconv.ParseUint(strpid, 10, 64)

	menu.Pid = uint(pid)

	dao.DB.Where("href = ? ", menu.Href).Where("id <> ?", menu.ID).First(&hrefck)

	if hrefck.ID > 0 {
		con.Error(c, "路由重复!")
		return
	}

	if menu.ID > 0 {
		//编辑
		dao.DB.Save(&menu)

		con.Success(c, "更新成功:id"+strconv.FormatUint(uint64(menu.ID), 10))
		return

	} else {
		dao.DB.Create(&menu)

		if menu.ID > 0 {
			con.Success(c, "添加成功,id:"+strconv.FormatUint(uint64(menu.ID), 10))
			return
		} else {
			con.Error(c, "添加失败")
			return
		}
	}

}

// 删除
func (con MenuController) MenuDel(c *gin.Context) {

	strid := c.DefaultQuery("id", "0")

	uintid, _ := strconv.ParseUint(strid, 10, 64)

	id := uint(uintid)

	if id <= 0 {
		con.Error(c, "参数错误")
		return
	}

	var adminMenu model.AdminMenu

	dao.DB.Where("id = ?", id).First(&adminMenu)

	if adminMenu.ID <= 0 {
		con.Error(c, "数据不存在")
		return
	}

	dao.DB.Delete(&adminMenu)

	con.Success(c, "删除成功,id:"+strconv.FormatUint(uint64(adminMenu.ID), 10))
}

// 获取菜单列表
func (con MenuController) GetMenuList(c *gin.Context) {

	var menulist []model.AdminMenu

	dao.DB.Order("sort asc").Find(&menulist)

	con.Success(c, "ok", menulist)
}

// 选择菜单获取列表
func (con MenuController) GetSelect(c *gin.Context) {

	var menuapi = model.AdminMenuApis{}

	dao.DB.Table("gin_admin_menu").Order("sort ASC").Scan(&menuapi)

	menuapi = preInsertSlice(model.AdminMenuApi{
		AdminMenu: model.AdminMenu{
			BaseModel: model.BaseModel{
				ID: 0,
			},
			Pid:   0,
			Title: "顶级菜单",
		},
	}, menuapi)

	treedata := menuapi.GetTree()

	var statusMap = make(map[string]interface{})

	statusMap["code"] = 200
	statusMap["message"] = "ok"

	c.JSON(http.StatusOK, gin.H{
		"status": statusMap,
		"data":   treedata,
	})
}

// 数组从前添加
func preInsertSlice(i model.AdminMenuApi, s model.AdminMenuApis) model.AdminMenuApis {
	res := append(model.AdminMenuApis{i}, s...)
	return res
}
